package com.example.busshop.entity;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import lombok.Getter;
import lombok.Setter;
import javax.persistence.*;
import java.util.Set;
import java.util.concurrent.atomic.AtomicReference;
@Setter
@Getter
@Entity
@Table(name = "customer")
@DiscriminatorValue("1")
@JsonIgnoreProperties(value={"hibernateLazyInitializer","handler","fieldHandler"})
public class Customer extends User {

    @OneToMany(mappedBy = "customer",
            fetch = FetchType.LAZY,
            cascade = CascadeType.ALL)
    @JsonIgnore
    private Set<Order> orders;

    public Order createOrder() {
        Order order = findUnpayOrder();
        if (order == null) {
            order = new Order();
            order.setStatus(0);
            orders.add(order);
        }
        return order;
    }
    public Order findUnpayOrder() {
        AtomicReference<Order> result = new AtomicReference<>(null);
        orders.forEach(order -> {
            if (order.getStatus().equals(0))
                result.set(order);
        });
        return result.get();
    }
    public Order cancelOrder(Order order){
        orders.remove(order);
        return order;
    }
}
